package com.mihuxiaobaigao.ai.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.mihuxiaobaigao.ai.Service.productService;
import com.mihuxiaobaigao.ai.pojo.*;
import com.mihuxiaobaigao.ai.pojo.Response.AiResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/project")
@Slf4j
public class productController {
    @Autowired
    private productService productService;

    // 放入元器件
    @PostMapping("/giveByName")
    public Result add(String name, @RequestParam(defaultValue = "1") Integer count) throws Throwable {
        productService.add(name,count);
        return Result.success();
    }

    // 取出元器件
    @PostMapping("/takeByName")
    public Result take(String name, @RequestParam(defaultValue = "1") Integer count) throws Throwable {
        String msg = productService.take(name,count);
        if(msg==null){
            return Result.success();
        }else if (msg.contains("仓库")){
            return Result.error(msg+"请重新确认取出物品数目");
        }else{
            return Result.success(msg);
        }
    }

    // 检索图片
    @GetMapping("/image/{productName}")
    public ResponseEntity<Resource> getProductImage(@PathVariable String productName) {
        String imagePath = "D:\\Compute\\java\\project1\\project\\ImgPackage";

        try {
            Path imageFilePath = Paths.get(imagePath, productName + ".jpg");
            File imageFile = imageFilePath.toFile();
            if (!imageFile.exists() || !imageFile.isFile()) {
                Path defaultImagePath = Paths.get(imagePath, "default.jpg");
                if (defaultImagePath.toFile().exists()) {
                    imageFile = defaultImagePath.toFile();
                } else {
                    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
                }
            }

            Resource resource = new FileSystemResource(imageFile);
            String contentType = Files.probeContentType(imageFilePath);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, contentType)
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 分页展示基本器件信息
    @GetMapping("/show")
    public Result show(@RequestParam(defaultValue = "0") Integer pageNum) throws IOException {
        int pageSize = 8;
        Page pageBean = productService.show(pageNum,pageSize);
        return Result.success(pageBean);
    }

    // 插入新的元器件
    @PostMapping("/insert")
    public Result insert(ProductDTO productDTO) {
        String msg = productService.insert(productDTO);
        if (msg != null) {
            return Result.error(msg);
        }
        return Result.success();
    }

    @GetMapping("/deleteByName")
    public Result deleteByName(String name) throws Throwable {
        productService.deleteByName(name);
        return Result.success();
    }

    // 获取元器件的 TAG 信息
    @GetMapping("/getTags")
    public Result getTags(String name) throws IOException {
        if (name == null) {
            return Result.error("未传递要查询的物品的名字");
        }
        Tags tags = productService.getTags(name);
        return Result.success(tags);
    }

    // 获取总进出量
    @GetMapping("/rating")
    public Result rating() throws IOException {
        return Result.success(productService.getRating());
    }

    // 获取元器件个数总数
    @GetMapping("/getAllCount")
    public Result getAllCount() throws IOException {
        int count = productService.getAllCount();
        return Result.success(count);
    }

    // 获取元器件类别总数
    @GetMapping("/getCount")
    public Result getCount() throws IOException {
        Integer allCount = productService.getCount();
        return Result.success(allCount);
    }

    // 获取 Bar 图内的基本信息
    @GetMapping("/getTips")
    public Result getTips() throws IOException {
        List<Map<String,Integer>> map = productService.getTips();
        return Result.success(map);
    }

    // 获取元器件的基本信息和数量
    @GetMapping("/getMsgAndCount")
    public Result getMsgAndCount(String name) throws IOException {
        if (name == null) {
            return Result.error("未收到name");
        }
        Map<String,Integer> map = productService.getMsgAndCount(name);
        return Result.success(map);
    }

    // 个数排序输出默认推荐
    @GetMapping("/normalRecommand")
    public Result normalRecommand(@RequestParam(defaultValue = "4") Integer count) throws IOException {
        Page pageBean = productService.normalRecommand(count);
        return Result.success(pageBean);
    }

    // 扩展推荐
    @GetMapping("/normalRecommandExpand")
    public Result normalRecommandExpand(@RequestParam(defaultValue = "15") Integer count) throws IOException {
        List<String> pageBean = productService.normalRecommandExpand(count);
        return Result.success(pageBean);
    }

    // 使用 TAG 检索元器件相关程度
    @PostMapping("/recommandByTags")
    public Result commandByTags(String name, @RequestParam(defaultValue = "4") Integer count) throws IOException {
        Page page =  productService.recommandByTags(name, count);
        return Result.success(page);
    }

    // 也是使用 TAG 进行元器件检索
    @PostMapping("/recommandProduct")
    public Result recommandProduct(String name) throws IOException {
        List<String> names = productService.recommandProduct(name);
        return Result.success(names);
    }

    // 进入到页面准备放入时确定需要提交到哪个箱子（负载因子计算）
    /*@PostMapping("/recommandBox")
    public Result recommandBox(String name) throws IOException {
        productService.recommandBox(name);

        return Result.success("暂未实现");
    }*/

    // 使用 AI 进行搜索后端服务（使用 LLM 进行分析）
    @PostMapping("/recommandProductAI")
    public Result recommandProductAI(String question,String userName) throws Throwable {
        AiResponse response = productService.recommandProductAI(question,userName);
        return Result.success(response);
    }

    @PostMapping("/setAgent")
    public Result setAgent(String app_id,String name) throws IOException {
        productService.setAgent(app_id,name);
        return Result.success();
    }

    @PostMapping("/setAuthorization")
    public Result setAuthorization(String authorization,String name) throws IOException {
        productService.setAuthorization(authorization,name);
        return Result.success();
    }

//    @PostMapping("/test")
//    public Result test(@RequestBody String matter) throws Throwable {
//        AiResponse test = productService.test(matter);
//        return Result.success(test);
//    }

}
